package hotel.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import hotel.entity.Category;
import hotel.entity.ItemDescription;
import hotel.entity.Payment;
import hotel.entity.Reserve;
import hotel.entity.Room;
import hotel.entity.Sales;
import hotel.entity.SalesLineItem;
import hotel.service.ICategoryService;
import hotel.service.IReserveService;
import hotel.service.ISalesService;
import util.HqlUtil;
import util.JSONUtil;

@Controller
public class ReserveController {

	@Autowired
	IReserveService<Reserve> reserveService;
	@Autowired
	ICategoryService<Category> categoryService;
	@Autowired
	ISalesService<Sales> salesService;
	
	@RequestMapping(value="reserveManagement")
	public String reserveManagement(Model model) {
		model.addAttribute("categoryList", categoryService.listAll("Category"));
		return "reserve/reservelist";
	}
	
	/**
	 * layui表格数据格式
	 * {code: 0,
	 * msg: "",
	 * count: 1000,
	 * data: []
	 * }
	 * page为第几页,limit为每页显示多少条数据
	 */
	@ResponseBody
	@RequestMapping(value = "reservelist")
	public String reserveList(Model model,int page,int limit,HttpServletRequest request) {
		String json=null;
		String op=request.getParameter("op");
		if(op!=null&&op.equals("search")) {//表单搜索
			//根据表单参数组装hql语句
			String hql=HqlUtil.assembleHqlForReserveForm(request.getParameterMap());
			List<Reserve> list=reserveService.list(hql);
			if(list==null) {
				json="{\"code\": 0,\"msg\":\"success\",\"count\": 0,\"data\":[]}";
			}
			else {
				json=JSONUtil.reserveListToJson(list);
				json="{\"code\": 0,\"msg\":\"success\",\"count\": "+list.size()+",\"data\":"+json+"}";	
			}
		}else {
			int totalCount=reserveService.getTotalCount("Reserve");
			int firstResult=(page-1)*limit;
			json=JSONUtil.reserveListToJson(reserveService.paging("Reserve", firstResult, limit));
			json="{\"code\": 0,\"msg\":\"success\",\"count\": "+totalCount+",\"data\":"+json+"}";
		}
		return json;
	}
	
	@RequestMapping(value="addReserve",method=RequestMethod.GET)
	public String add(Model model) {
		model.addAttribute("categoryList", categoryService.listAll("Category"));
		return "reserve/add";
	}
	
	@ResponseBody
	@RequestMapping(value="addReserve",method=RequestMethod.POST)
	public String addReserve(Reserve reserve) {
		if(reserveService.save(reserve))
			return JSONUtil.returnSuccess();
		else
			return JSONUtil.returnFailure();
	}
		
	@RequestMapping(value="editReserve",method=RequestMethod.GET)
	public String edit(int reserveid,Model model) {
		model.addAttribute("reserve", reserveService.findById(Reserve.class, reserveid));
		model.addAttribute("categoryList", categoryService.listAll("Category"));
		return "reserve/edit";
	}
		
	@ResponseBody
	@RequestMapping(value="editReserve",method=RequestMethod.POST)
	public String editReserve(Reserve reserve) {
		System.out.println(reserve.getReserveTime().toString());
		if(reserveService.update(reserve))
			return JSONUtil.returnSuccess();
		return JSONUtil.returnFailure();
	}
		
	@ResponseBody
	@RequestMapping(value="deleteReserve")
	public String deleteReserve(int reserveid) {
		if(reserveService.deleteById("Reserve", reserveid))
			return JSONUtil.returnSuccess();
		else
			return JSONUtil.returnFailure();
	}
	
	@RequestMapping(value="checkin",method=RequestMethod.GET)
	public String checkin(int reserveid,Model model) {
		Reserve reserve=reserveService.findById(Reserve.class, reserveid);
		model.addAttribute("reserve", reserve);
		model.addAttribute("amount", reserve.getAmount());
		return "reserve/checkin";
	}
	
	@ResponseBody
	@RequestMapping(value="checkin",method=RequestMethod.POST)
	public String saveCheckin(HttpServletRequest request,Sales sales,Payment payment,Reserve reserve) {
		List<SalesLineItem> salesLineItemList=new ArrayList<SalesLineItem>();
		String[] counts=request.getParameterValues("count");
		String[] customerNames=request.getParameterValues("customerName");
		String[] id_numbers=request.getParameterValues("id_number");
		String[] teles=request.getParameterValues("tele");
		String[] roomids=request.getParameter("roomids").split(",");
		double price=Double.parseDouble(request.getParameter("price"));
		
		for(int i=0;i<sales.getAmount();i++) {
			SalesLineItem item=new SalesLineItem();
			int count=Integer.parseInt(counts[i]);
			item.setCount(count);
			Room room=new Room();
			room.setRoomid(Integer.parseInt(roomids[i]));
			item.setRoom(room);
			item.setPrice(price);
			salesLineItemList.add(item);
			
			String[] temp_name=customerNames[i].split(",");
			String[] temp_number=id_numbers[i].split(",");
			String[] temp_tele=teles[i].split(",");
			for(int j=0;j<count;j++) {
				ItemDescription desc=new ItemDescription();
				desc.setCustomerName(temp_name[j]);
				desc.setId_number(temp_number[j]);
				desc.setTele(temp_tele[j]);
				item.getDescriptions().add(desc);
				//desc.setSalesLineItem(item);
			}
		}
		sales.setReserve(reserve);//销售关联预定
		
		reserveService.updateReserveState(reserve.getReserveid());//更新预定状态-'已入住'
		
		if(salesService.save(sales, salesLineItemList,payment))
			return JSONUtil.returnSuccess();
		else
			return JSONUtil.returnFailure();
	}
}
